package com.neusoft.nep.NEPM.controller;


import com.neusoft.nep.entity.Gridder;
import com.neusoft.nep.entity.nepgResult;
import com.neusoft.nep.entity.nepsFeedback;
import com.neusoft.tools.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;

import static com.neusoft.tools.FeedbackUtils.getAllFeedback;
import static com.neusoft.tools.FileUtils.*;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.neusoft.tools.FileUtils;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class publicAqiDataListViewController {
    @FXML
    private TableColumn<nepsFeedback,String>coldata,colnumber,colusername,colphoneNumber,coldone,colprovince,colcity,coladdress,collevel,colcontent;
    private ObservableList tableList= FXCollections.observableArrayList();
    @FXML
    private TableView tableView;
    @FXML
    private Button back;
    @FXML
    private TreeView treeview;
    @FXML
    private Button btn_out;
    @FXML
    private TreeItem To_AqiTrendTotalStatisView;
    @FXML
    private TreeItem To_AqiSeperatedStatisView;
    @FXML
    private TreeItem To_OtherStatisView;
    @FXML
    private TreeItem To_ProvinceDataTotalStatisView;
    @FXML
    private Button assign,details,delete;
    @FXML
    private TreeItem To_confirmDataView;
    @FXML
    private TreeItem To_publicAqiDataList;
    @FXML
    private List<nepsFeedback> fbs = new ArrayList<>();
    @FXML
    private ComboBox<String> provinces, cities;

    @FXML
    public void initialize() throws IOException {

        fbs = getAllFeedback();

        tableView.setItems(tableList);
        colphoneNumber.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
        colusername.setCellValueFactory(new PropertyValueFactory<>("username"));
        coldata.setCellValueFactory(new PropertyValueFactory<>("date"));
        colcity.setCellValueFactory(new PropertyValueFactory<>("city"));
        colprovince.setCellValueFactory(new PropertyValueFactory<>("province"));
        collevel.setCellValueFactory(new PropertyValueFactory<>("level"));
        colnumber.setCellValueFactory(new PropertyValueFactory<>("number"));

        tableList.setAll(fbs); // 使用 setAll 更高效

        setupComboBoxListeners();

        tableView.setEditable(true);
        colusername.setCellFactory(TextFieldTableCell.forTableColumn());
        setupTreeViewListeners(); // 将 TreeView 逻辑封装一下更清晰
        treeview.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == To_AqiSeperatedStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/AqiSeperatedStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            } else if (newValue == To_AqiTrendTotalStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/AqiTrendTotalStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            } else if (newValue == To_OtherStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/OtherStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            } else if (newValue == To_ProvinceDataTotalStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/ProvinceDataTotalStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }

            }

            else if (newValue == To_confirmDataView) {
                try {
                    FXMLUtils.switchToShow(btn_out, "NEPM/view/confirmDataView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            }else if (newValue == To_publicAqiDataList) {
                try {
                    FXMLUtils.switchToShow(btn_out, "NEPM/view/publicAqiDataList.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            }
        });
    }
    /**
     * 封装 TreeView 的监听器设置
     */
    private void setupTreeViewListeners() {
        treeview.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {

            if (newValue == To_AqiSeperatedStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/AqiSeperatedStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            }
        });
    }

    /**
     * 设置省份和城市 ComboBox 的监听器，以实现联动和查询
     * @throws IOException 如果地址文件读取失败
     */
    private void setupComboBoxListeners() throws IOException {

        Map<String, List<String>> addressMap = AddressMapUtils.initAddressMap();

        provinces.setItems(FXCollections.observableArrayList(addressMap.keySet()));

        provinces.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
            if (newValue != null) {

                cities.getSelectionModel().clearSelection();
                cities.getItems().clear();

                List<String> cityList = addressMap.get(newValue);
                if (cityList != null) {
                    cities.setItems(FXCollections.observableArrayList(cityList));
                }

                queryData();
            }
        });

        // 添加对【城市 ComboBox】的监听
        cities.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
            // 只有当城市被有效选择后，才执行查询
            if (newValue != null) {
                queryData();
            }
        });
    }

    public void Log_out() throws IOException {
        FXMLLoader fxmlLoader=new FXMLLoader();
        URL url=getClass().getResource("../view/LogInView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene=new Scene(root);
        Stage stage = (Stage) btn_out.getScene().getWindow();
        stage.setScene(scene);
        stage.show();
    }
    public void delfeedback() throws IOException {
        nepsFeedback selectedFeedback = (nepsFeedback) tableView.getSelectionModel().getSelectedItem();
        tableList.remove(selectedFeedback);
        fbs.remove(selectedFeedback);
        AlertUtils.showDialog("删除信息","删除成功");
        System.out.println("out");
    }
    public void assign() throws IOException {
        // 获取选中的 nepsFeedback 对象
        nepsFeedback selectedFeedback = (nepsFeedback) tableView.getSelectionModel().getSelectedItem();
        if (selectedFeedback != null) {
            FXMLLoader fxmlLoader = new FXMLLoader();
            URL url = getClass().getResource("../view/assignView.fxml");
            fxmlLoader.setLocation(url);
            Parent root = fxmlLoader.load();
            Scene scene = new Scene(root);
            // 获取目标场的 Controller
            assignViewController detailController = fxmlLoader.getController();
            // 传递选中的 nepsFeedback 对象
            detailController.setNepsFeedback(selectedFeedback);
            Stage stage = (Stage) assign.getScene().getWindow();
            stage.setScene(scene);
            stage.show();
        } else {
            // 处理未选中任何行的情况
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告");
            alert.setHeaderText(null);
            alert.setContentText("请先选择一条反馈信息。");
            alert.showAndWait();
        }
    }
    public void details() throws IOException {
        // 获取选中的 nepsFeedback 对象
        nepsFeedback selectedFeedback = (nepsFeedback) tableView.getSelectionModel().getSelectedItem();

        if (selectedFeedback != null) {
            FXMLLoader fxmlLoader = new FXMLLoader();
            URL url = getClass().getResource("../view/detailOfAqiVIew.fxml");
            fxmlLoader.setLocation(url);
            Parent root = fxmlLoader.load();
            Scene scene = new Scene(root);

            // 获取目标场景的 Controller
            detailOfAqiViewController detailController = fxmlLoader.getController();
            // 传递选中的 nepsFeedback 对象
            detailController.setNepsFeedback(selectedFeedback);

            Stage stage = (Stage) details.getScene().getWindow();
            stage.setScene(scene);
            stage.show();
        } else {
            // 处理未选中任何行的情况
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告");
            alert.setHeaderText(null);
            alert.setContentText("请先选择一条反馈信息。");
            alert.showAndWait();
        }
    }
    public void back() throws IOException {
        FXMLLoader fxmlLoader=new FXMLLoader();
        URL url=getClass().getResource("../view/ManagerUIView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene=new Scene(root);
        Stage stage = (Stage)back.getScene().getWindow();
        stage.setScene(scene);
        stage.show();}

    public void queryData() {
        String selectedProvince = provinces.getSelectionModel().getSelectedItem();
        String selectedCity = cities.getSelectionModel().getSelectedItem();

        List<nepsFeedback> filteredData = fbs.stream()
                .filter(feedback -> {
                    boolean provinceMatch = (selectedProvince == null) || selectedProvince.equals(feedback.getProvince());

                    boolean cityMatch = (selectedCity == null) || selectedCity.equals(feedback.getCity());

                    return provinceMatch && cityMatch;
                })
                .collect(Collectors.toList());

        tableList.setAll(filteredData);

    }

}


